'use strict';

const path = require('path');
const fs = require('fs');
const fsExtra = require('fs-extra');
const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath');

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);

// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
const publicUrlOrPath = getPublicUrlOrPath(
  process.env.NODE_ENV === 'development',
  '.',
  process.env.PUBLIC_URL
);

const buildPath = process.env.BUILD_PATH || 'out/web';

const moduleFileExtensions = [
  'web.mjs',
  'mjs',
  'web.js',
  'js',
  'web.ts',
  'ts',
  'web.tsx',
  'tsx',
  'json',
  'web.jsx',
  'jsx',
];

// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
  const extension = moduleFileExtensions.find(extension =>
    fs.existsSync(resolveFn(`${filePath}.${extension}`))
  );

  if (extension) {
    return resolveFn(`${filePath}.${extension}`);
  }

  return resolveFn(`${filePath}.js`);
};

const pages = {
  report_admin: {
    name: 'report_admin',
    appHtml: resolveApp('public/index_luckysheet.html'),
    appIndexJs: resolveModule(resolveApp, 'src/pages/report_admin/index'),
  },
  report: {
    name: 'report',
    appHtml: resolveApp('public/index_luckysheet.html'),
    appIndexJs: resolveModule(resolveApp, 'src/pages/report/index'),
  }
};

function scanPages(pages) {
  const dirs = fs.readdirSync(resolveApp('src/pages/'));
  dirs.forEach((file) => {
    const state = fs.statSync(resolveApp('src/pages/' + file))
    if (state.isDirectory()) {
      if (!(file in pages)) {
        pages[file] = {
          name: file,
          appHtml: resolveApp('public/index.html'),
          appIndexJs: resolveModule(resolveApp, `src/pages/${file}/index`),
        }
      }
    }
  })
}
scanPages(pages);

// config after eject: we're in ./config/
const paths = {
  dotenv: resolveApp('.env'),
  appPath: resolveApp('.'),
  appBuild: resolveApp(buildPath),
  appPublic: resolveApp('public'),
  // appHtml: resolveApp('public/index.html'),
  // appIndexJs: resolveModule(resolveApp, 'src/pages/report_admin/index'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  appTsConfig: resolveApp('tsconfig.json'),
  appJsConfig: resolveApp('jsconfig.json'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveModule(resolveApp, 'src/pages/setupTests'),
  proxySetup: resolveApp('src/pages/setupProxy.js'),
  appNodeModules: resolveApp('node_modules'),
  appWebpackCache: resolveApp('node_modules/.cache'),
  appTsBuildInfoFile: resolveApp('node_modules/.cache/tsconfig.tsbuildinfo'),
  swSrc: resolveModule(resolveApp, 'src/service-worker'),
  publicUrlOrPath,
  // web app pages
  pages,
  // electron app paths
  mainEntryJs: resolveModule(resolveApp, 'src/main/main'),
  renderEntryJs: resolveModule(resolveApp, 'src/renderer/renderer'),
  renderHtml: resolveApp('public/index.html'),
  preloadJs: resolveModule(resolveApp, 'src/main/preload')
};

module.exports = paths;

module.exports.moduleFileExtensions = moduleFileExtensions;

function copyPublicFolder(dest) {
  const htmls = [];
  Object.keys(paths.pages).forEach((key) => {
    const page = paths.pages[key];
    htmls.push(page.appHtml);
  });
  fsExtra.copySync(paths.appPublic, dest, {
    dereference: true,
    filter: file => !htmls.includes(file),
  });
}

module.exports.copyPublicFolder = copyPublicFolder;